<template>
  <div class="login">
    <el-form ref="formRef" :inline="true" :model="form" :rules="loginRules" class="demo-form-inline">
      <el-form-item label="Username" prop="username">
        <el-input v-model="form.username" placeholder="Approved by" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitFn">Login</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import {reactive, ref} from "vue";
import request from "@/api/request";
import { ElMessage } from 'element-plus'

const form = reactive({
  username: 'norman'
})

const action = ref('form')

const name = ref('Jeon')

const validatePass = (rule, value, callback) => {
  if (!/^[a-zA-Z]+$/.test(value)) {
    callback(new Error('The input must be English characters!'))
  } else{
    callback()
  }
}

// loginRole校验表单规则
const loginRules = reactive({
  username: [
      { required: true, trigger: 'blur', message: 'User name cannot be empty!' },
    { validator: validatePass, trigger: 'blur' }
  ],
})


// 轮询查询线程
const timing = ()=>{
  setInterval(()=>{
    queryThreads()
  },5000)
}

const formRef = ref()

const submitFn = function (){
  formRef.value.validate((valid) => {
    if (valid) {
      userInfoFn(form.username).then((rep)=>{
        name.value = rep.data.name
        action.value = 'list'
        queryThreads()
        timing()
      }).catch((e)=>{
        ElMessage.warning(e.response.data.error)
      })
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

const userInfoFn = (username)=>{
  return request({
    url: '/api/users/'+username,
    method:'get',
  })
}

const threads = ref()
// 获取线程列表
const getTheadsFn = ()=>{
  return request({
    url: '/api/threads',
    method:'get',
  })
}

const queryThreads = ()=>{
  getTheadsFn().then((rep)=>{
    // threads.value = rep.data
    threads.value = rep.data
    changePopoverPost()
    // console.info(threads.value)
  })
}

// 动态更新post弹出框
const popoverPost = ref({})

const changePopoverPost = ()=>{
  for (let ky in threads) {
    popoverPost[threads[ky].id] = false
  }
}

</script>

<style>
.head-tab{
  display: flex;
  justify-content: flex-end;

}
.login {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
